package pkg

import (
	"flag"
	"fmt"
	"github.com/go-ini/ini"
	"log"
	"reflect"
)

type App struct {
	RuntimePath string
	LogSavePath string
	LogSaveName string
	LogFileExt  string
	TimeFormat  string
}

var AppSetting = &App{}

type DataBase struct {
	User     string
	Password string
	Host     string
	DbName   string
}

var DbSetting = &DataBase{}

type flagStruct struct {
	Model string `usage:"runtime model debug or release"`
	Port  int    `usage:"server runtime port"`
	Env   string `usage:"server runtime environment(dev,fat,uat or prod)"`
}

var FlagConfig = &flagStruct{}

var FilePath = ""
var cfg *ini.File

func InitConfigSetup(unitTestFilePath ...string) {
	reflectTypeof := reflect.TypeOf(*FlagConfig)
	flag.StringVar(
		&FlagConfig.Model, "model", "release",
		reflectTypeof.Field(0).Tag.Get("usage"),
	)
	flag.IntVar(
		&FlagConfig.Port, "port", 7500,
		reflectTypeof.Field(1).Tag.Get("usage"),
	)

	flag.StringVar(
		&FlagConfig.Env, "env", "dev",
		reflectTypeof.Field(2).Tag.Get("usage"),
	)
	// 解析命令行参数
	flag.Parse()

	var err error
	// 兼容单元测试动态设置文件地址
	if len(unitTestFilePath) != 0 {
		FilePath = unitTestFilePath[0]
	}
	// 加载配置文件
	cfg, err = ini.Load(FilePath + fmt.Sprintf("config/env.%s.ini", FlagConfig.Env))
	if err != nil {
		log.Fatalf("config.ini ': %v", err)
	}

	mapTo("app", AppSetting)
	mapTo("database", DbSetting)
}

func mapTo(section string, v interface{}) {
	err := cfg.Section(section).MapTo(v)
	if err != nil {
		log.Fatalf("Cfg.MapTo %s err: %v", section, err)
	}
}
